package vip.xiaonuo.issued.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.core.util.IpAddressUtil;
import vip.xiaonuo.core.util.OkHttpUtils;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.facedoor.vo.dewo.*;
import vip.xiaonuo.facedoor.iservice.IFaceDoorDtoService;
import vip.xiaonuo.facedoor.vo.haiqing.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import vip.xiaonuo.issued.util.HQHttpUtil;

@Service(RuleConstant.HQ + RuleConstant.FACEDOOR_DTO)
@Slf4j
public class HQFaceDoorDtoServiceImpl implements IFaceDoorDtoService {

    @Override
    public DeviceStateResponse getDeviceState(String uri) throws Exception {
       return null;
    }

    @Override
    public ReturnJson addPerson(String uri, AddPersonRequest addPersonRequest) throws Exception {
//        return addOrUpdate(uri, addPersonRequest.getHqAddPersonRequest(), addPersonRequest.getRequestHeader(), "新增人员【{}】成功！", "新增人员");
        addPersonRequest.getHqAddPersonRequest().setOperator("AddPerson");
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/AddPerson"),
                        JSON.toJSONString(addPersonRequest.getHqAddPersonRequest()),
                        addPersonRequest.getRequestHeader().getUserName(),
                        addPersonRequest.getRequestHeader().getPassWord());

        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
        if (ObjectUtil.equal(baseResponse.getCode(), 200)) {
            return new ReturnJson().setCode("0000").setMsg("success");
        }else if (ObjectUtil.equal(baseResponse.getCode(),466)) {
            UpdatePersonRequest updatePersonRequest = new UpdatePersonRequest();
            updatePersonRequest.setHqAddPersonRequest(addPersonRequest.getHqAddPersonRequest());
            updatePersonRequest.setRequestHeader(addPersonRequest.getRequestHeader());
            this.updatePerson(uri,updatePersonRequest);
            return new ReturnJson().setCode("0000").setMsg("success");
        } else if (ObjectUtil.equal(baseResponse.getCode(),477)){
            return new ReturnJson().setCode("477").setMsg("人员信息有误!");
        }else {
            throw new ServiceException(
                    500,
                    "新增人员" + addPersonRequest.getHqAddPersonRequest().getInfo().getName()+" 失败信息： code:"
                            + baseResponse.getCode()
                            + " message:  "
                            + Optional.ofNullable(baseResponse.getInfo().getResult())
                            .orElse("")
                            + " "
                            + Optional.ofNullable(baseResponse.getInfo().getDetail())
                            .orElse(""));
        }

    }

    private static ReturnJson addOrUpdate(String uri, HQAddPersonRequest addPersonRequest, RequestHeader addPersonRequest1, String message, String type) throws Exception {
        return null;
    }

    @Override
    public ReturnJson deletePerson(String uri, DeletePersonRequest deletePersonRequest) throws Exception {

        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/DeletePerson"),
                JSON.toJSONString(deletePersonRequest.getHqDeletePersonRequest()),
                deletePersonRequest.getRequestHeader().getUserName(),
                deletePersonRequest.getRequestHeader().getPassWord());

        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
        if (ObjectUtil.equal(baseResponse.getCode(), 200)) {
            log.info("删除人员【{}】成功！",deletePersonRequest.getHqDeletePersonRequest().getInfo().getCustomizeID());
            return new ReturnJson().setCode("0000").setMsg("success");
        } else {
            throw new ServiceException(
                500,
                "删除人员"+deletePersonRequest.getHqDeletePersonRequest().getInfo().getCustomizeID()+" 失败信息： code:"
                    + baseResponse.getCode()
                    + " message:  "
                    + Optional.ofNullable(baseResponse.getInfo().getResult())
                    .orElse("")
                    + " "
                    + Optional.ofNullable(baseResponse.getInfo().getDetail())
                    .orElse(""));
        }
    }

    @Override
    public ReturnJson deleteAllPerson(String uri, DeletePersonRequest deletePersonRequest) throws Exception {
        DeleteAllPersonRequest deleteAllPersonRequest = new DeleteAllPersonRequest();
        DeleteAllPersonRequest.InfoDTO infoDTO = new DeleteAllPersonRequest.InfoDTO();
        deleteAllPersonRequest.setInfo(infoDTO);
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/DeleteAllPerson"),
                JSON.toJSONString(deleteAllPersonRequest),
                deletePersonRequest.getRequestHeader().getUserName(),
                deletePersonRequest.getRequestHeader().getPassWord());

        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
        if (ObjectUtil.equal(baseResponse.getCode(), 200)) {
            log.info("删除全部人员成功!！");
            return new ReturnJson().setCode("0000").setMsg("success");
        } else {
            throw new ServiceException(
                500,
                "删除全部人员失败"+" 失败信息： code:"
                    + baseResponse.getCode()
                    + " message:  "
                    + Optional.ofNullable(baseResponse.getInfo().getResult())
                    .orElse("")
                    + " "
                    + Optional.ofNullable(baseResponse.getInfo().getDetail())
                    .orElse(""));
        }
    }

    @Override
    public ReturnJson updatePerson(String uri, UpdatePersonRequest updatePersonRequest) throws Exception {
//        return addOrUpdate(uri, updatePersonRequest.getHqAddPersonRequest(), updatePersonRequest.getRequestHeader(), "修改人员【{}】成功！", "修改人员");
        updatePersonRequest.getHqAddPersonRequest().setOperator("EditPerson");
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/EditPerson"),
                        JSON.toJSONString(updatePersonRequest.getHqAddPersonRequest()),
                        updatePersonRequest.getRequestHeader().getUserName(),
                        updatePersonRequest.getRequestHeader().getPassWord());

        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
        if (ObjectUtil.equal(baseResponse.getCode(), 200)) {
            return new ReturnJson().setCode("0000").setMsg("success");
        } else if (ObjectUtil.equal(baseResponse.getCode(),464)) {
            AddPersonRequest addPersonRequest = new AddPersonRequest();
            addPersonRequest.setHqAddPersonRequest(updatePersonRequest.getHqAddPersonRequest());
            addPersonRequest.setRequestHeader(updatePersonRequest.getRequestHeader());
            this.addPerson(uri,addPersonRequest);
            return new ReturnJson().setCode("0000").setMsg("success");
        } else if (ObjectUtil.equal(baseResponse.getCode(),477)){
            return new ReturnJson().setCode("477").setMsg("人员信息有误!");
        }else {
            throw new ServiceException(
                    500,
                    "修改人员" + updatePersonRequest.getHqAddPersonRequest().getInfo().getName()+" 失败信息： code:"
                            + baseResponse.getCode()
                            + " message:  "
                            + Optional.ofNullable(baseResponse.getInfo().getResult())
                            .orElse("")
                            + " "
                            + Optional.ofNullable(baseResponse.getInfo().getDetail())
                            .orElse(""));
        }
    }

    @Override
    public GetPersonResponse getPerson(String uri, GetPersonRequest getPersonRequest) throws Exception {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("queryType", "1");
        queryMap.put("key", "ABCD1234");
        queryMap.put("personnelId", getPersonRequest.getPersonnelId());
        return OkHttpUtils.requestDevice(OkHttpUtils.ReqType.GET, uri.concat("/query_personnels"), queryMap, GetPersonResponse.class);
    }

    @Override
    public GetPersonResponse listPerson(String uri, GetPersonRequest request) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("key", "ABCD1234");
        param.put("queryType", "2");
        param.put("page", request.getPage());
        param.put("limit", request.getLimit());
        return OkHttpUtils.requestDevice(OkHttpUtils.ReqType.GET, uri.concat("/query_personnels"), param, GetPersonResponse.class);
    }

    @Override
    public BaseResponse setUserPwd(String uri, SetUserPwdRequest setUserPwdRequest, RequestHeader requestHeader)
            throws Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/SetUserPwd"),
                        JSON.toJSONString(setUserPwdRequest),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse setFactoryDefault(
            String uri, SetFactoryDefaultRequest setFactoryDefaultRequest, RequestHeader requestHeader)
            throws IOException, Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/SetFactoryDefault"),
                        JSON.toJSONString(setFactoryDefaultRequest),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse setSysTime(String uri, SetSysTimeRequest setSysTimeRequest, RequestHeader requestHeader)
            throws Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/SetSysTime"),
                        JSON.toJSONString(setSysTimeRequest),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse openDoor(String uri, OpenDoorRequest setSysTimeRequest, RequestHeader requestHeader)
            throws Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/OpenDoor"),
                        JSON.toJSONString(setSysTimeRequest),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public GetAndSetGeneralParamRequest getGeneralParam(String uri, RequestHeader requestHeader)
            throws Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/GetGeneralParam"),
                        JSON.toJSONString(""),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, GetAndSetGeneralParamRequest.class);
    }

    @Override
    public GetAndSetDoorCondition getDoorCondition(String uri, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/GetDoorCondition"),
                JSON.toJSONString(""),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, GetAndSetDoorCondition.class);
    }

    @Override
    public BaseResponse setDoorCondition(String uri, GetAndSetDoorCondition getAndSetDoorCondition, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/SetDoorCondition"),
                JSON.toJSONString(getAndSetDoorCondition),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public GetAndSetSoundRequest getSound(String uri, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/GetSound"),
                JSON.toJSONString(""),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, GetAndSetSoundRequest.class);
    }

    @Override
    public BaseResponse setSound(String uri, GetAndSetSoundRequest getAndSetSoundRequest, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/SetSound"),
                JSON.toJSONString(getAndSetSoundRequest),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse setSubscribe(String uri, SetSubscribeRequest setSubscribeRequest, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/Subscribe"),
                JSON.toJSONString(setSubscribeRequest),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse setGeneralParam(String uri, GetAndSetGeneralParamRequest getAndSetGeneralParamRequest, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
                .postJsonParams(
                        uri.concat("/action/SetGeneralParam"),
                        JSON.toJSONString(getAndSetGeneralParamRequest),
                        requestHeader.getUserName(),
                        requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    @Override
    public BaseResponse rebootDevice(String uri, RebootDeviceRequest rebootDeviceRequest, RequestHeader requestHeader) throws Exception {
        String response = HQHttpUtil.getInstance()
            .postJsonParams(
                uri.concat("/action/RebootDevice"),
                JSON.toJSONString(rebootDeviceRequest),
                requestHeader.getUserName(),
                requestHeader.getPassWord());
        return JSON.parseObject(response, BaseResponse.class);
    }

    public static void main(String[] args) {
        System.out.println(Base64.encode("admin:test"));
    }
}
